package com.truonghau.xmeasure.commons;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.format.DateFormat;
import android.util.Log;

import com.truonghau.model.SmsDTO;
import com.truonghau.smstoxls.R;
import com.truonghau.smstoxls.activity.MyGPSActivity;
import com.truonghau.smstoxls.service.AlarmService_Service;

public class SmSUtils {
	private static final String ERROR_CODE_0 = "0";
	private static final String ERROR_CODE_A = "So lieu khu A khong chinh xac";
	private static final String ERROR_CODE_B = "So lieu khu B khong chinh xac";
	private static final String ERROR_CODE_C = "So lieu khu C khong chinh xac";
	public static void processMessage(final Context context, final SmsMessage smsMessage) {
		//check new file
		checkNewFile(context, smsMessage);

		//Check sematic
		SmsDTO sms = getObjecSms(smsMessage);
		if(!ERROR_CODE_0.equals(sms.getErrorCode())){
			//gui lai thong bao cho nhan vien
			sendSMS(context, sms.getErrorCode());
		}else{
			//append 1 line
			FileUtil.appendLineXLS(Constants.PATH_THSOFT + convertToFileName(smsMessage.getTimestampMillis()), sms, checkNewInDay(context, sms));
		}
	}
	private static boolean checkNewInDay(Context context, SmsDTO sms){
		boolean isNewDate = false;
		Date d_today = new Date();
		String date = convertToDate(d_today.getTime());
		String dateShort_today = date.substring(0, 7);
		//load
		SharedPreferences settings = context.getSharedPreferences(
				Constants.PREFS_NAME, 0);
		String txtToday_temp = settings.getString(Constants.TxtToday, "");
		if(txtToday_temp.startsWith(dateShort_today)){
			isNewDate = false;
		}else{
			try {

				SharedPreferences.Editor editor = settings.edit();
				editor.putString(Constants.TxtToday,
						dateShort_today);
				editor.commit();
				isNewDate = true;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.getMessage());
			}

		}
		return isNewDate;
	}
	public static boolean checkForNotif(Context context){
		boolean chuaNhanDuocTinNhan = true;
		Date date = new Date();
		String fullDate = convertToDate(date.getTime());
		String dateShort = fullDate.substring(0, 7);
		//load
		SharedPreferences settings = context.getSharedPreferences(
				Constants.PREFS_NAME, 0);
		String tempInRef = settings.getString(Constants.TxtToday, "");
		if(tempInRef.startsWith(dateShort)){
			chuaNhanDuocTinNhan = false;
		}else{
			chuaNhanDuocTinNhan = true;
		}
		return chuaNhanDuocTinNhan;
	}
	private static SmsDTO getObjecSms(final SmsMessage sms){
		String str = sms.getMessageBody();
		str = str.replace(";", ":");
		String[] arr = str.split(":");
		int size = arr.length;
		long khuA = 0;
		long khuB = 0;
		long khuC = 0;
		String errorCode = ERROR_CODE_0;
		try {
			khuA = Long.parseLong(arr[1].trim());
		} catch (Exception e) {
			errorCode += ERROR_CODE_A;
		}
		try {
			khuB = Long.parseLong(arr[2].trim());
		} catch (Exception e) {
			if(size >2){
				errorCode += ", " + ERROR_CODE_B;
			}
		}
		try {
			khuC = Long.parseLong(arr[3].trim());
		} catch (Exception e) {
			if(size >3){
				errorCode += ", " + ERROR_CODE_C;
			}
		} 
		Date date = new Date();
		SmsDTO ret = new SmsDTO(-1, convertToDate(date.getTime()), khuA, khuB, khuC);
		ret.setErrorCode(errorCode);
		return ret;
	}
	private static void checkNewFile(Context context, final SmsMessage sms){
		File folder = new File(Constants.PATH_THSOFT);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		File fileXls = new File(Constants.PATH_THSOFT + convertToFileName(sms.getTimestampMillis())); 
		if (!fileXls.exists()) {
			try {
				List<String> listHeader = new ArrayList<String>();//{"stt","sysdate","khu A","khu B", "khu C", "tong so"};
				listHeader.add("STT");
				listHeader.add("Ngày");
				listHeader.add("Khu A");
				listHeader.add("Khu B");
				listHeader.add("Khu C");
				listHeader.add("Tổng số");
				FileUtil.createFileXLS(Constants.PATH_THSOFT + convertToFileName(sms.getTimestampMillis()),listHeader,context);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static void sendSMS(final Context context, String message)
	{        
		//load
		SharedPreferences settings = context.getSharedPreferences(
				Constants.PREFS_NAME, 0);
		String txtTelNumberStr = settings.getString(Constants.TxtTelNumber, "");

		//end
		SmsManager sms = SmsManager.getDefault();
		try {
			sms.sendTextMessage("tel:"+txtTelNumberStr, null, message, null, null);        
		} catch (Exception e) {
			Log.e("error", "Invalid number " + txtTelNumberStr + "?");
		}
	}

	private static String convertToDate(Long str){
		return DateFormat.format("dd/MM/yy-hh:mm:ss", str).toString();
	}
	private static String convertToFileName(Long str){
		return DateFormat.format("'kd_'yyyy'_'MM'.xls'", str).toString();
	}
	public static void showNotification(Context context, NotificationManager mNM, String sms) {
		// In this sample, we'll use the same text for the ticker and the expanded notification
		CharSequence text = sms;//"Alarm service started";

		// Set the icon, scrolling text and timestamp
		Notification notification = new Notification(R.drawable.iconlogo, text,
				System.currentTimeMillis());

		// The PendingIntent to launch our activity if the user selects this notification
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				new Intent(context, MyGPSActivity.class), 0);

		// Set the info for the views that show in the notification panel.
		notification.setLatestEventInfo(context, "Thông báo",
				text, contentIntent);
		// Send the notification.
		// We use a layout id because it is a unique number.  We use it later to cancel.
		mNM.notify(R.string.alarm_service_started, notification);
	}

	public static void startSMSAlert(Context context){
		PendingIntent mAlarmSender = PendingIntent.getService(context,
				0, new Intent(context, AlarmService_Service.class), 0);
		long firstTime = SystemClock.elapsedRealtime();
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
				firstTime,30*60*1000 , mAlarmSender);  

	}
}
